﻿using Microsoft.EntityFrameworkCore;
using rbac.domain.Entity;
using rbac.domain.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace rbac.domain.Impl
{
    public class PermissionRepository : IPermissionRepository
    {
        RbacContext db;

        public PermissionRepository(RbacContext db)
        {
            this.db = db;
        }

        public int Add(Permission entity)
        {
            db.Permissions.Add(entity);
            return db.SaveChanges();
        }
        public int Update(Permission entity)
        {
            var role = db.Permissions.FirstOrDefault(x => x.Id == entity.Id);
            role.PermissionName = entity.PermissionName;
            role.Remark = entity.Remark;
            role.UpdateTime = DateTime.Now;
            return db.SaveChanges();
        }

        public IQueryable<Permission> Permissions()
        {
            return db.Permissions;
        }

        public List<Permission> GetPermission(string permissionName)
        {
            var permiss = db.Permissions.AsQueryable().ToList();
            if (!string.IsNullOrEmpty(permissionName))
            {
                permiss = permiss.Where(x => x.PermissionName.Contains(permissionName)).ToList();
            }

            return permiss.ToList();
        }

        public int Delete(int loginUserId, params int[] idlist)
        {
            if (idlist.Length <= 0)
            {
                return 0;
            }
            var roles = db.Permissions.Where(x => idlist.Contains(x.Id));
            foreach (var role in roles)
            {
                role.IsDeleted = true;
                role.UpdatedUserId = loginUserId;
                role.UpdateTime = DateTime.Now;
            }
            return db.SaveChanges();
        }
    
    }
}
